import Vue from 'vue';
import VueRouter, { RouterOptions } from 'vue-router';
import Util from '../core/utils/Utils';
import Ajax from "../core/utils/ajax"
//import Cookies from 'js-cookie'
import { routers, appRouters, otherRouters } from './routers'

Vue.use(VueRouter);

const RouterConfig: RouterOptions = {
  mode: 'history',
  routes: routers
};

export const router = new VueRouter(RouterConfig);

router.beforeEach((to, from, next) => {

  console.info("from:" + from.path + "---to:" + to.path);
  console.info(from);
  console.info(to);
  //  iView.LoadingBar.start();
  Util.title(to.meta.title);
  const lock = Util.getCookieValue('locking');
  if (to.path == "/" || to.path.split('/')[1] == "ui") {
    console.info("ui router");
    next()
  }
  else if (Util.abp && Util.abp.session.userId && lock === "1" && to.name !== 'locking') {
    next({
      replace: true,
      name: 'locking'
    });
  } else if (Util.abp && Util.abp.session.userId && to.name == "login") {
    next({
      name: 'home'
    });
  }
  else {
    console.info("else router");
    const curRouterObj = Util.getRouterObjByName([otherRouters, ...appRouters], to.name);
    if (curRouterObj && curRouterObj.permission) {
      if (Util.hasPermission(curRouterObj.permission)) {
        Util.toDefaultPage([otherRouters, ...appRouters], to.name, router, next);
      } else {
        next({
          replace: true,
          name: 'error-403'
        });
      }
    } else {
      Util.toDefaultPage([...routers], to.name, router, next);
    }
  }


  /* if (Util.getCookieValue('locking') === '1' && to.name !== 'locking') {
    next({
      replace: true,
      name: 'locking'
    });
  } else if (Util.getCookieValue('locking') === '0' && to.name === 'locking') {
    next(false);
  } else {
    if (Util.abp && !Util.abp.session.userId && to.name !== 'login') {
      next({
        name: 'login'
      });
    } else if (Util.abp && !Util.abp.session.userId && to.name === 'login') {
      Util.title(to.meta.title);
      next({
        name: 'home'
      });
    } else {
      const curRouterObj = Util.getRouterObjByName([otherRouters, ...appRouters], to.name);
      if (curRouterObj && curRouterObj.permission) {
        if (Util.hasPermission(curRouterObj.permission)) {
          Util.toDefaultPage([otherRouters, ...appRouters], to.name, router, next);
        } else {
          next({
            replace: true,
            name: 'error-403'
          });
        }
      } else {
        Util.toDefaultPage([...routers], to.name, router, next);
      }
    }
  } */
});
router.afterEach((to) => {
  if (to.path != "/" && to.path.split('/')[1] == "ui") {
    Util.openNewPage(router.app, to.name, to.params, to.query);
    // iView.LoadingBar.finish();
    window.scrollTo(0, 0);
  }


});